# -*- coding: utf-8 -*- 
import wx,os
import settings, dot
from utility import *
from dot import *
from resulttable import ResultFrame
from calalldots import Calculator_all_dots
from calcrab import *
from calfish import *

class MainFrame(wx.Frame):
    
    def __init__(self):
        wx.Frame.__init__(self, None, -1, "FishRuler: 水生动物形态学数据测量软件", size=(600, 380), 
                          style = wx.SYSTEM_MENU | wx.CAPTION | wx.CLOSE_BOX | wx.MINIMIZE_BOX,
                          pos = (settings.screenWidth/4 , settings.screenHeight/4))
        
        self.dots = dot.Dot()
        self.dotsWin = dot.DotsWin(self, self.dots)
        
        self.resultWin = None
        
        self.createMenuBar()
        self.createToolBar()
        self.initStatusBar()
        
    #something weried will happen    
    def OnOpen( self, event ):
        
        dlg = wx.FileDialog(self, "打开图片", settings.cur_dir, style=wx.OPEN)
        if dlg.ShowModal() == wx.ID_OK:
            
            filename = dlg.GetPath()
            settings.cur_dir = os.path.dirname(filename)
            image = f2image(filename)
            self.dotsWin.set_image(image)
            self.SetClientSize( (image.GetWidth() , image.GetHeight()) )
            settings.unit = "pixel"
    
    def OnSave( self, event ):pass
    def OnQuit( self, event ):
        self.Destroy()
        
    def OnUnit( self, event ):
        units = {u"像素 pixel":"pixel", u"厘米 cm":"cm"}
        mb = self.GetMenuBar()
        itemId = event.GetId()
        item = mb.FindItemById(itemId)
        s = item.GetLabel().strip() 
        settings.unit = units[s]
        #print settings.unit
        
    def OnGetScale( self, event ):
        dlg = wx.MessageDialog(None, "1 cm = %s 像素"%str(settings.scale), "当前比例尺", style=wx.OK)
        dlg.ShowModal()
        dlg.Destroy()
        #print settings.scale
        
    def OnSetScale( self, event ):
        dia = wx.TextEntryDialog(None, "设置比例尺:1 cm = ? 像素", "比例换算", str(settings.scale), style=wx.OK|wx.CANCEL)
        if dia.ShowModal() == wx.ID_OK:
            settings.scale = float(dia.GetValue())
            #settings.unit = "cm"
        dia.Destroy()
        
    def OnDotType( self, event ):
        types = {u"圆点":"dot", u"十字":"crux"}
        mb = self.GetMenuBar()
        itemId = event.GetId()
        item = mb.FindItemById(itemId)
        s = item.GetLabel().strip()
        settings.dot_type = types[s]
        self.dotsWin.redraw()
        
    def OnColor( self, event ):
        colors = {u"红色":"red", u"黑色":"black", u"蓝色":"blue", u"绿色":"green"}
        
        mb = self.GetMenuBar()
        itemId = event.GetId()
        item = mb.FindItemById(itemId)
        if not item:
            toolbar = self.GetToolBar()
            item = toolbar.FindById(itemId)
            color = item.GetShortHelp()
            settings.dot_color = color
            #print color
        else:
            s = item.GetLabel().strip()
            #print s
            settings.dot_color = colors[s]
            
        self.dotsWin.redraw()
        
    #def OnOtherColor(self,event):pass
    def OnClear( self, event ):
        self.dotsWin.clear_dots()
        
    def OnCalAllDots(self,event):
        
        if self.resultWin:
            self.resultWin.Destroy()
            
        c = Calculator_all_dots(self.dots)
        c.get_ready()
        self.resultWin = ResultFrame(c)
        self.resultWin.Show(True)
            
    def OnCalFish7Dots(self,event):
        
        if self.resultWin:
                self.resultWin.Destroy()
        c = Calculator_7Dots(self.dots)
        c.get_ready()
        self.resultWin = ResultFrame(c)
        self.resultWin.Show(True)
        
    def OnCalFishFramework(self,event):
        if self.resultWin:
                self.resultWin.Destroy()
        c = Calculator_Fish_Framework(self.dots)
        c.get_ready()
        self.resultWin = ResultFrame(c)
        self.resultWin.Show(True) 
    def OnCalGuiFishFramework(self,event):
        if self.resultWin:
                self.resultWin.Destroy()
        c = Calculator_GuiFish_Framework(self.dots)
        c.get_ready()
        self.resultWin = ResultFrame(c)
        self.resultWin.Show(True) 
               
    def OnCalCrabBack(self,event):
        #print c.result
        if self.resultWin:
            self.resultWin.Destroy()
        c = Calculator_crab_back(self.dots)
        c.get_ready()
        self.resultWin = ResultFrame(c)
        self.resultWin.Show(True)
        
    def OnCalCrabBelly(self,event):
        if self.resultWin:
            self.resultWin.Destroy()
        c = Calculator_crab_belly(self.dots)
        c.get_ready()
        self.resultWin = ResultFrame(c)
        self.resultWin.Show(True)
        
    def OnMagnifier(self,event):
        mb = self.GetMenuBar()
        itemId = event.GetId()
        item = mb.FindItemById(itemId)
        
        if item.IsChecked():
            settings.magnifier_on = True
        else:
            settings.magnifier_on = False
        
    def menuData(self):
        return [  ("文件", (
                    ("打开", "打开需要测量的鱼虾图片文件", self.OnOpen),
                    ("保存", "保存图片文件", self.OnSave),
                    ("", "", ""),
                    ("退出", "退出", self.OnQuit))),

                  ("计算", (
                      ("所有点间的距离", "计算图片上标记所有点之间距离", self.OnCalAllDots),
                      ('','',''),
                      ("计算鱼类体长等7个形态学指标", "鱼类7个指标:全长,体长,叉长,头长,吻长,眼径,尾柄长", self.OnCalFish7Dots),
                      ("鱼类(白鱼类)框架数据", "请先标记鱼体框架测量定位点", self.OnCalFishFramework),
                      ("鱼类(鳜鱼类)框架数据", "请先标记鱼体框架测量定位点", self.OnCalGuiFishFramework),
                      ('','',''),
                      ("河蟹头胸甲背部参数","河蟹头胸甲背部参数",self.OnCalCrabBack),
                      ("河蟹腹甲参数","河蟹头胸甲背部参数",self.OnCalCrabBelly),
                      )),
          
                  ("设置",(
                    ("数据单位",(
                            ("像素 pixel", "设置计算数据的单位为像素", self.OnUnit, wx.ITEM_RADIO),
                            ("厘米 cm", "设置计算数据的单位为厘米", self.OnUnit, wx.ITEM_RADIO)
                            )),
                    ("比例尺",(
                        ("设置","图片中像素距离与实际距离的换算",self.OnSetScale),
                        ("显示当前比例尺","显示当前比例尺",self.OnGetScale ))),
                    #("", "", ""),
                    ("放大镜", "开启 or 关闭放大镜", self.OnMagnifier, wx.ITEM_CHECK),)),
                  
                  ('标记点', (
                       ('标记点类型', (
                                 ('圆点', '设置标记点的图案为圆点', self.OnDotType, wx.ITEM_RADIO), 
                                 ('十字','设置标记点的图案为圆点', self.OnDotType, wx.ITEM_RADIO))),
                       ("标记点颜色", (
                               ("黑色", "设置标记点的颜色为黑色", self.OnColor, wx.ITEM_RADIO),
                               ("红色", "设置标记点的颜色为红色", self.OnColor, wx.ITEM_RADIO),
                               ("绿色", "设置标记点的颜色为绿色", self.OnColor, wx.ITEM_RADIO),
                               ("蓝色", "设置标记点的颜色为蓝色", self.OnColor, wx.ITEM_RADIO))),
                               #("其他...", "其他颜色", self.OnOtherColor, wx.ITEM_RADIO))),
                        
                        ("", "", ""),
                       
                        ("清空","清空图片上所有的点", self.OnClear)))
                ]
    def createMenuBar( self ):
        menuBar = wx.MenuBar()
        for eachMenuData in self.menuData():
            menuLabel = eachMenuData[0]
            menuItems = eachMenuData[1]
            menuBar.Append( self.createMenu( menuItems ), menuLabel )
            self.SetMenuBar( menuBar )
            
    def createMenu( self, menuData ):
        menu = wx.Menu()
        for eachItem in menuData:
            if len( eachItem ) == 2:
                label = eachItem[0]
                subMenu = self.createMenu( eachItem[1] )
                menu.AppendMenu( wx.NewId(), label, subMenu )
            else:
                self.createMenuItem( menu, *eachItem )
        return menu
    
    def createMenuItem(self, menu, label, status, handler, kind=wx.ITEM_NORMAL):
        if not label:
            menu.AppendSeparator()
            return
        menuItem = menu.Append(-1, label, status, kind)
        self.Bind(wx.EVT_MENU, handler, menuItem)
    
    def toolbarData(self):
        return (("打开", "icons/open.bmp","选择并打开需要测量的鱼虾图片文件", self.OnOpen),
                ("保存", "icons/save.bmp","保存图片文件", self.OnSave),
                ("", "", "", ""),
                ("计算", "icons/cal.bmp", "计算图片上标记所有点之间距离", self.OnCalAllDots))
    def toolbarColorData(self):
        return ("Black", "Red", "Green", "Blue")
    def createToolBar(self):
        toolbar = self.CreateToolBar()
        for each in self.toolbarData():
            self.createSimpleTool(toolbar, *each)
        toolbar.AddSeparator()
        for each in self.toolbarColorData():
            self.createColorTool(toolbar, each)
        toolbar.Realize()
    def createSimpleTool(self, toolbar, label, filename, help, handler):
        if not label:
            toolbar.AddSeparator()
            return
        bmp = wx.Image(filename, wx.BITMAP_TYPE_BMP).ConvertToBitmap()
        tool = toolbar.AddSimpleTool(-1, bmp, label, help)
        self.Bind(wx.EVT_MENU, handler, tool)
    def createColorTool(self, toolbar, color):
        bmp = self.MakeBitmap(color)
        tool = toolbar.AddRadioTool(-1, bmp, shortHelp=color)
        self.Bind(wx.EVT_MENU, self.OnColor, tool)
    def MakeBitmap(self, color):
        bmp = wx.EmptyBitmap(16, 15)
        dc = wx.MemoryDC()
        dc.SelectObject(bmp)
        dc.SetBackground(wx.Brush(color))
        dc.Clear()
        dc.SelectObject(wx.NullBitmap)
        return bmp

    def initStatusBar(self):
        self.statusbar = self.CreateStatusBar()
        self.statusbar.SetFieldsCount(2)
        self.statusbar.SetStatusWidths([-1, -2])
        self.statusbar.SetStatusText("左键点击标记位置,右键点击清除标记点,Enjoy!^_^", 1)
        
